//
//  OAuthViewController.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/8.
//  Copyright © 2015年 hzj. All rights reserved.
//

import UIKit
import SVProgressHUD


class OAuthViewController: UIViewController,UIWebViewDelegate {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        
        view = webView
        webView.delegate = self
        view.backgroundColor = UIColor.whiteColor()
        title = "新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "closeTheWindow")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
    }
    
    
    //MARK: - webView的代理方法
      func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        
        SVProgressHUD.dismiss()
        
        let urlstring = request.URL!.absoluteString
        
        
        //不包含回调地址时
        if !urlstring.hasPrefix(NetworkTool.sharedTool.redirectURL){
            return true
        }
        //获得请求码code
        if let query = request.URL!.query where query.hasPrefix("code="){
            let code = query.substringFromIndex("code=".endIndex)
            
            printLog("请求码=\(code)")
            UserAccountViewModel.sharedUserAccountViewModel.loadTheUserAccount(code).subscribeError({ (error) -> Void in
                printLog(error)
                }, completed: { () -> Void in
                    printLog("成功")
                    SVProgressHUD.dismiss()
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //利用通知跳转到欢迎界面
                        NSNotificationCenter.defaultCenter().postNotificationName(HZJselectTheControllerNotification, object: nil)
                    })
            })
//            NetworkTool.sharedTool.loadTheToken(code).subscribeNext({ (result) -> Void in
////                printLog(result)
//                //字典转模型
//                let account = UserAccount(dict: result as! [String : AnyObject])
//                
//                printLog(account)
////                printLog("测试")
//                //用包含token的返回值请求更多信息
//                self.getTheUserInfo(account)
//                }, error: { (error) -> Void in
////                    print(error)
//                    printLog(error, logError: true)
//            })
        }else{
            print("取消")
        }

//        print(request)
        
        return false
    }
    
    //获取更多信息
    func getTheUserInfo(account:UserAccount){
        NetworkTool.sharedTool.loadTheUserInfo(account.uid!).subscribeNext({ (result) -> Void in
            
            let dic = result as! [String:AnyObject]
            account.name = dic["name"] as? String
            account.avatar_large = dic["avatar_large"] as? String
            printLog(account)
            
            account.saveTheUserAccount()
            
            /*
            //只能获取到name和avatar_large
            let userinfo = UserAccount(dict: result as! [String : AnyObject])
            printLog(userinfo)
            */
            
            }, error: { (error) -> Void in
                printLog(error, logError: true)
            }) { () -> Void in
                
        }
    }
    
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
                // 加载授权页
        webView.loadRequest(NSURLRequest(URL: NetworkTool.sharedTool.urlString))

    }
    
    //“关闭”的功能
    @objc private func closeTheWindow(){
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true) { () -> Void in
        }
    }
    //"自动填充"的功能
    @objc private func autoFill(){
        
        let str = "document.getElementById('userId').value = '18782985775';" + "document.getElementById('passwd').value = 'h220651020f';"
//        print(str)
        webView.stringByEvaluatingJavaScriptFromString(str)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
}
